package com.android.lovely.ext

import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.pm.ResolveInfo
import android.net.Uri
import android.text.Html
import android.text.format.DateUtils
import android.text.method.LinkMovementMethod
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.browser.customtabs.CustomTabsIntent
import androidx.browser.customtabs.CustomTabsService
import androidx.core.content.ContextCompat.getSystemService
import androidx.core.graphics.toColorInt
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.android.lovely.R
import com.android.lovely.framework.BaseWebActivity
import com.android.lovely.framework.UIController.showToast
import com.kotlin.extensions.appContext
import com.kotlin.extensions.context.ActivityExt.navBarColor
import com.kotlin.extensions.context.ActivityExt.navBarLightMode
import com.kotlin.extensions.context.ActivityExt.statusBarColor
import com.kotlin.extensions.context.ActivityExt.statusBarLightMode
import com.kotlin.extensions.context.ContextExt.startPage
import java.text.SimpleDateFormat
import java.util.Locale

val windowBackground = "#FF0A0B14".toColorInt()
fun Activity.windowBackgroundNav() {
    navBarColor = windowBackground
    navBarLightMode = false
}

fun Activity.windowBackgroundStatus() {
    statusBarColor = windowBackground
    statusBarLightMode = false
}

/**
 *
 * @author why
 * @date 2025/3/8 01:27
 */
inline fun View.startWebView(title: String, url: String) {
    runCatching {
        val serviceIntent = Intent(CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION)
        val resolveInfoList: List<ResolveInfo> =
            context.packageManager.queryIntentServices(serviceIntent, 0)
        val hasCustomTab = resolveInfoList.isNotEmpty()
        if (hasCustomTab) {
            val builder = CustomTabsIntent.Builder()
            builder.setToolbarColor(resources.getColor(R.color.black))
            builder.setNavigationBarColor(resources.getColor(R.color.black))
            builder.setShareState(CustomTabsIntent.SHARE_STATE_OFF)
            builder.setUrlBarHidingEnabled(true)
            val customTabsIntent = builder.build()
            customTabsIntent.launchUrl(context, Uri.parse(url))
            return
        }
    }
    context.startPage<BaseWebActivity>("title" to title, "url" to url)
}

inline fun Context.startWebView(title: String, url: String) {
    runCatching {
        val serviceIntent = Intent(CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION)
        val resolveInfoList: List<ResolveInfo> =
            packageManager.queryIntentServices(serviceIntent, 0)
        val hasCustomTab = resolveInfoList.isNotEmpty()
        if (hasCustomTab) {
            val builder = CustomTabsIntent.Builder()
            builder.setToolbarColor(resources.getColor(R.color.black))
            builder.setNavigationBarColor(resources.getColor(R.color.black))
            builder.setShareState(CustomTabsIntent.SHARE_STATE_OFF)
            builder.setUrlBarHidingEnabled(true)
            val customTabsIntent = builder.build()
            customTabsIntent.launchUrl(this, Uri.parse(url))
            return
        }
    }
    startPage<BaseWebActivity>("title" to title, "url" to url)
}

/**
 * 从当前 View 的上下文获取 Activity
 */
fun ViewGroup.getActivity(): AppCompatActivity? {
    var context = context
    while (context is ContextWrapper) {
        if (context is AppCompatActivity) {
            return context
        }
        context = context.baseContext
    }
    return null
}

fun SwipeRefreshLayout.init() {
    setColorSchemeColors(appContext.getColor(R.color.color_main))
}

fun Long.format(): String {
    val isToday = DateUtils.isToday(this)
    val isYesterday = DateUtils.isToday(this + 24 * 60 * 60 * 1000)
    return when {
        isToday -> SimpleDateFormat(
            "HH:mm",
            Locale.getDefault()
        ).format(this)

        isYesterday -> "${appContext.getString(R.string.yesterday)} ${
            SimpleDateFormat(
                "HH:mm",
                Locale.getDefault()
            ).format(this)
        }"

        else -> SimpleDateFormat(
            "yyyy-MM-dd HH:mm",
            Locale.getDefault()
        ).format(this)
    }
}

fun String.copy(context: Activity) {
    val clipboardManager =
        context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    val clipData = ClipData.newPlainText("label", this)
    clipboardManager.setPrimaryClip(clipData)
    showToast(context.getString(R.string.copied_id))
}

fun String.share() {
    runCatching {
        val intent = Intent()
        intent.action = Intent.ACTION_SEND
        intent.putExtra(Intent.EXTRA_TEXT, this)
        intent.type = "text/plain"
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        appContext.startActivity(intent)
    }
}

fun TextView.setSysText(text: String) {
    val formattedText = text
        .replace(Regex("\\[(https?://[\\w./-]+)]")) { matchResult ->
            matchResult.value.removeSurrounding("[", "]")
        }.replace("\r\n", "\n")
    this.text = Html.fromHtml(formattedText, Html.FROM_HTML_MODE_LEGACY)
//    movementMethod = LinkMovementMethod.getInstance()
}